package cn.edu.scnu.semart.user.controller;
import cn.edu.scnu.semart.common.result.Result;
import cn.edu.scnu.semart.common.utils.JwtUtils;
import cn.edu.scnu.semart.common.utils.MD5;
import cn.edu.scnu.semart.model.user.User;
import cn.edu.scnu.semart.user.service.UserService;
import cn.edu.scnu.semart.vo.user.LoginRespVo;
import cn.edu.scnu.semart.vo.user.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Api(tags = "认证登录")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private UserService userService;

    /**
     * 登录：普通用户 / 管理员共用
     * 返回：token
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<String> login(@Valid @RequestBody LoginVo vo) {
        User user = userService.lambdaQuery()
                .eq(User::getUsername, vo.getUsername())
                .one();
//        System.out.println("数据库密码"+user.getPassword());
//        System.out.println("vo密码"+MD5.encrypt(vo.getPassword()));
        if (user == null) {
            return Result.fail("用户为空");
        }if( !user.getPassword().equals(MD5.encrypt(vo.getPassword()))){
            return Result.fail("密码错误");
        }
        if(user.getStatus()==User.UserStatus.BANNED){
            return Result.fail("账号被封禁");
        }
        if (user.getStatus() != User.UserStatus.ACTIVE) {
            return Result.fail("账号已被禁用");
        }

        // 生成 JWT：载荷里放 userId 和 userType
        String token = JwtUtils.createToken(user.getUserId(), user.getUserType().name());
        // 返回脱敏信息
        LoginRespVo resp = new LoginRespVo(
                token,
                user.getUserId(),
                user.getUsername(),
                user.getUserType().name(),
                user.getEmail(),
                user.getPhone(),
                user.getStatus().getValue()
        );
        return (Result<String>) (Object)Result.ok(resp);
    }

    /**
     * 退出：前端丢弃 token 即可；这里预留拉黑逻辑
     */
    @PostMapping("/logout")
    @ApiOperation("退出")
    public Result<Void> logout(HttpServletRequest request) {
        // 如需 Redis 黑名单：String token = request.getHeader("Authorization");
        return Result.ok(null);
    }
}